namespace RBAC.Write.Api.Application.Handler.BomHandler
{
    using System;
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.BomCommand;

    /// <summary>
    /// 产品编辑 处理器
    /// </summary>
    public class ProductUpdateHandler : IRequestHandler<ProductUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Product> _productRepo;
        private readonly ILogger<ProductUpdateHandler> _logger;

        public ProductUpdateHandler(IBaseRepository<Product> productRepo, ILogger<ProductUpdateHandler> logger)
        {
            _productRepo = productRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(ProductUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (request.Id <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品Id无效", Data = 0 });
                if (string.IsNullOrWhiteSpace(request.Name))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品名称不能为空", Data = 0 });

                // 获取产品并校验存在且未删除
                var product = _productRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { request.Id });
                if (product == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品不存在或已删除", Data = 0 });

                // 更新允许变更的字段
                product.Name = request.Name!.Trim();
                product.Model = request.Model;
                product.Description = request.Description;

                var rows = _productRepo.Update(product);
                result.Code = rows > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = rows > 0 ? "编辑产品成功" : "编辑产品失败";
                result.Data = rows;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("编辑产品被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "编辑产品异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "编辑产品异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
